<?php

/**
 * This is the model class for table "Item".
 *
 * The followings are the available columns in table 'Item':
 * @property integer $id
 * @property integer $productId
 * @property integer $reserveeId
 * @property integer $quantity
 * @property string $created
 * @property string $updated
 * @property integer $deleted
 *
 * Related records:
 * @property Product $product
 * @property array $reservations
 * @property integer $reservedCount
 */
class Item extends ActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Item the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{Item}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('productId', 'required'),
			array('productId, quantity', 'numerical', 'integerOnly'=>true),
			array('created, updated, deleted', 'safe'),
			array('id, productId, quantity, created, updated', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array(
			'product' => array(self::BELONGS_TO, 'Product', 'productId'),
			'reservations' => array(self::HAS_MANY, 'Reservation', 'itemId'),
			'reservedCount' => array(self::STAT, 'Reservation', 'itemId',
				'select'=>'SUM(quantity)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => Yii::t('label','Id'),
			'productId' => Yii::t('label','Product'),
			'quantity' => Yii::t('label','Quantity'),
			'created' => Yii::t('label','Created'),
			'updated' => Yii::t('label','Updated'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->with[] = 'product';

		$criteria->compare('id',$this->id);
		$criteria->compare('product.name',$this->productId,true);
		$criteria->compare('quantity',$this->quantity);
		$criteria->compare('created',$this->created,true);
		$criteria->compare('updated',$this->updated,true);

		$criteria->addCondition('t.deleted=0');

		return new CActiveDataProvider(get_class($this),array(
			'criteria'=>$criteria,
		));
	}

	public function getRemainingQuantity()
	{
		$reservations=Reservation::model()->findAll('itemId='.$this->id);

		$quantity=$this->quantity;

		if($reservations!==array())
			foreach($reservations as $reservation)
				$quantity-=$reservation->quantity;

		return $quantity;
	}
}
